import requests
import os

# 下载目录
root_path = 'F:/test4/'


#  下载图片
def download_img(url, pathname, fname):
    root = root_path + pathname + "/"

    filename = url.split("/")[-1]
    filename = filename[0:filename.find('?')]

    path = root + fname + filename
    print(url)
    try:
        if not os.path.exists(root):
            os.makedirs(root)
        if not os.path.exists(path):
            headers = {
                'Upgrade-Insecure-Requests': '1',
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'}

            r = requests.get(url, headers=headers, timeout=3)
            r.raise_for_status()
            print('picture name :'+path + ' dir path :'+root)
            # 使用with语句可以不用自己手动关闭已经打开的文件流
            with open(path, "wb") as f:  # 开始写文件，wb代表写二进制文件
                f.write(r.content)
            print("爬取完成")
        else:
            print("文件已存在")
    except Exception as e:
        print("爬取失败:" + str(e))
